/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.bullionxpress.client.view;

import com.bullionxpress.shared.util.Log;
import java.awt.BorderLayout;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import com.bullionxpress.client.application.ClientGlobals;
import com.bullionxpress.shared.model.Account;
import com.bullionxpress.shared.listeners.AccountEvent;
import com.bullionxpress.shared.listeners.AccountListener;
import com.bullionxpress.shared.service.MarketService;
import com.bullionxpress.shared.model.Order;
import com.bullionxpress.server.impl.OrderManager;
import com.bullionxpress.shared.service.OrderService;

/**
 *
 * @author BullionXpress.com
 */
public class OrderListView extends JPanel implements AccountListener {

    JTable table = null;
    //Account account = null;
    GenericTableModel model = new GenericTableModel();
    private static final int INSTRUMENT = 0;
    private static final int ORDER_ID = 1;
    private static final int STATUS = 2;
    private static final int ORDER_TYPE = 3;
    private static final int EXPIRY = 4;
    private static final int UNITS = 5;
    private static final int QUANTITY_FILLED = 6;
    private static final int QUANTITY_REMAINING = 7;
    private static final int PRICE = 8;
    //private static final int TOTAL = 8;

    public OrderListView() {
        //this.account = account;
        ClientGlobals.cm.addAccountListener(this);
        String[] columnNames = new String[]{"Instrument", "Order Id", "Status", "Order Type", "Expiry", "Units", "Quantity Filled", "Units Remaining", "Price"};
        for (int i = 0; i < columnNames.length; i++) {
            model.addColumn(columnNames[i]);
        }

        table = new JTable(model);
        //table.setEnabled(false);

        TableColumnModel tcm = table.getColumnModel();
        //TODO: REFACTOR
        tcm.getColumn(UNITS).setCellRenderer(new NumberCellRenderer());
        tcm.getColumn(QUANTITY_FILLED).setCellRenderer(new NumberCellRenderer());
        tcm.getColumn(QUANTITY_REMAINING).setCellRenderer(new NumberCellRenderer());
        tcm.getColumn(PRICE).setCellRenderer(new DollarCellRenderer());
        //tcm.getColumn(9).setCellRenderer(new DollarCellRenderer());
        setLayout(new BorderLayout());
        add(table.getTableHeader(), BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(table);
        //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        add(scrollPane, BorderLayout.CENTER);
    }

    public boolean containsOrder(String oid) {
        try {
            for (int i = 0; i < model.getRowCount(); i++) {
                String id = (String) model.getValueAt(i, ORDER_ID);
                if (id.equals(oid)) {
                    return true;
                }
            }
        } catch (Exception ex) {
        }
        return false;
    }

    private int getOrderRow(String id) {
        for (int i = 0; i < model.getRowCount(); i++) {
            String v = (String) model.getValueAt(i, ORDER_ID);
            if (id.equals(v)) {
                return i;
            }
        }
        return -1;
    }

    private void updateOrder(Order o) {
        int target = getOrderRow(o.getId());
        if (target != -1) {
            try {
                DecimalFormat format = new DecimalFormat("$#,##0.00");
                //model.setValueAt(format.format(pnl), target, ORDER_ID);
                model.setValueAt(o.getStatus(), target, STATUS);
                //System.out.println(o.getRemainingUnits());
                model.setValueAt(o.getRemainingUnits(), target, QUANTITY_REMAINING);
                model.setValueAt(o.getQuantityFilled(), target, QUANTITY_FILLED);
                model.setValueAt(new Double(o.getPrice()), target, PRICE);
                //model.setValueAt(o.getPrice(), target, PRICE);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    public void update(AccountEvent ae) {
        try {
            OrderService om = ClientGlobals.orderService;

            java.util.Queue q = om.getOrderQueueByAccount(ClientGlobals.account.getId());
            int sz = q.size();
            //Log.info("Account Queue Size:" + sz);
            Object[] data = q.toArray();
            DecimalFormat format = new DecimalFormat("$#,##0.00");
            for (int i = 0; i < sz; i++) {
                Order o = (Order) data[i];
                Date d = o.getExpiry();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String ts = formatter.format(d);

                if (!containsOrder(o.getId())) {
                    Object[] row = new Object[]{
                        o.getInstrument(), o.getId(), o.getStatus(), o.getOrderType(), ts, o.getUnits(), o.getQuantityFilled(), o.getRemainingUnits(), new Double(o.getPrice())
                    };
                    model.addRow(row);
                } else {
                    updateOrder(o);
                }
            }

            if (model.getRowCount() != q.size()) {
                //System.out.println("That is odd:" + model.getRowCount() + " " + sz);
            }

        } catch (Exception ex) {
            Log.info(ex);
            ex.printStackTrace();
        }
    }
}
